<?php

namespace app\common\model\xilumarket;

use think\Db;
use think\Exception;
use think\Log;
use think\Model;



class ProductCity extends Model
{
    // 表名
    protected $name = 'xilumarket_product_city';

    protected $autoWriteTimestamp = false;

    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;


    /**
     * @param Product $product
     * @param int $productId
     * @return bool|string
     */
    public static function add($product, $areasIds) {

        try {
            $ids = [];
            foreach ($areasIds as $prov_id=>$cities){
                foreach ($cities as $city){
                    $exit = self::field("id")->where('province_id',$prov_id)->where('product_id',$product->id)->where('city_id',$city)->find();
                    if($exit){
                        $ids = $exit['id'];
                        continue;
                    }else{
                        $result = self::create([
                            'province_id'   =>  $prov_id,
                            'product_id'    =>  $product->id,
                            'city_id'    =>  $city,
                        ]);
                        $ids[] = $result['id'];
                    }
                }
            }
            self::where('product_id',$product->id)->whereNotIn('id',$ids)->delete();
        }catch (\Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            return false;
        }
        return true;
    }


    /**
     * @param Object $product
     * @param int $productId
     * @return bool|string
     */
    public static function admin_add($product, $cityIds) {

        $cityIds = $cityIds && is_string($cityIds) ? explode(',',$cityIds) :[];
        try {
            $ids = [];
            foreach ($cityIds as $cityId){
                $prov_id = Area::where('id',$cityId)->value('pid');
                $exit = self::field("id")->where('province_id',$prov_id)->where('product_id',$product->id)->where('city_id',$cityId)->find();
                if($exit){
                    $ids = $exit['id'];
                    continue;
                }else{
                    $result = self::create([
                        'province_id'   =>  $prov_id,
                        'product_id'    =>  $product->id,
                        'city_id'    =>  $cityId,
                    ]);
                    $ids[] = $result['id'];
                }
            }
            self::where('product_id',$product->id)->whereNotIn('id',$ids)->delete();
        }catch (Exception $e) {
            Log::error($e->getMessage()."\n".$e->getTraceAsString());
            return false;
        }
        return true;
    }


}
